let express = require('express');
let router = express.Router();
let mongoose = require('mongoose');
let panModel = require('../models/pants')


//管理员注册
router.post('/register',function(req,res,next){

  let userName= req.body.userName
  let userPwd= req.body.userPwd
  let userId= Math.floor(Math.random()*10)+'62'+Math.floor(Math.random()*10+10)+'001';
  let param= {
      userId: userId,
      userName: userName,
      userPwd: userPwd,
      
  }
panModel.create(
  param,
  function(err){
   if(err){
     res.json({
       status: '1',
       msg: err.message
     })
   }else{
     res.json({
       status:'0',
       msg:'',
       result:'用户注册成功'
     })
   }
  }
)
})
//管理员登录
router.post('/login',function(req,res,next){
  let param = {
    userName: req.body.userName,
    userPwd: req.body.userPwd
  };
  panModel.findOne(param,function(err,doc){
    if(err){
      res.json({
        status: '0',
        msg:err.message,
        result:''
      })
    }else{
      if(doc){
       //将userId存入cookie
        res.cookie('userId',doc.userId,{
          path:'/',
          maxAge: 1000*60*60*24*20
        });
        //将userName存入cookie
        res.cookie('userName',doc.userName,{
          path:'/',
          maxAge: 1000*60*60*24*20
        });
        res.json({
          status:'0',
          msg:'',
          result:{
            userName:doc.userName,
          }
        })
      }
    }
  })
})
//管理员退出接口
router.post('/logout',function(req,res,next){
  res.cookie('userId','',{
    path:'/',
    maxAge: -1
  });
  res.cookie('userName','',{
    path:'/',
    maxAge: -1
  });
  res.json({
    status: '0',
    msg:'',
    result:'退出成功'
  })
})

 module.exports = router;